package com.zhaoqi.hr.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaoqi.hr.config.WechatConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class WechatUtil {
    
    private static final Logger log = LoggerFactory.getLogger(WechatUtil.class);
    
    @Autowired
    private WechatConfig wechatConfig;
    
    @PostConstruct
    public void init() {
        log.info("WechatUtil初始化 - AppID: {}, AppSecret: {}, ApiUrl: {}", 
                wechatConfig.getAppId(), 
                wechatConfig.getAppSecret() != null ? "***" : "null", 
                wechatConfig.getApiUrl());
    }
    
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 获取微信session信息
     */
    public WechatSessionInfo getWechatSession(String code) {
        log.info("=== 调用微信API获取session信息 ===");
        log.info("输入code: {}", code);
        
        
        try {
            log.info("微信配置信息 - apiUrl: {}, appId: {}, appSecret: {}", 
                    wechatConfig.getApiUrl(), wechatConfig.getAppId(), 
                    wechatConfig.getAppSecret() != null ? "***" : "null");
            
            String url = String.format("%s/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    wechatConfig.getApiUrl(),
                    wechatConfig.getAppId(),
                    wechatConfig.getAppSecret(),
                    code);
            
            log.info("请求微信API: {}", url.replaceAll("secret=[^&]*", "secret=***"));
            
            String response = restTemplate.getForObject(url, String.class);
            log.info("微信API响应: {}", response);
            
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(response);
            
            if (jsonNode.has("errcode")) {
                int errcode = jsonNode.get("errcode").asInt();
                String errmsg = jsonNode.get("errmsg").asText();
                throw new RuntimeException("微信API错误: " + errcode + " - " + errmsg);
            }
            
            WechatSessionInfo sessionInfo = new WechatSessionInfo();
            sessionInfo.setOpenid(jsonNode.get("openid").asText());
            sessionInfo.setSessionKey(jsonNode.get("session_key").asText());
            
            log.info("获取到openid: {}, sessionKey: {}", sessionInfo.getOpenid(), sessionInfo.getSessionKey());
            log.info("=== 微信session获取成功 ===");
            
            return sessionInfo;
            
        } catch (Exception e) {
            log.error("获取微信session失败", e);
            throw new RuntimeException("获取微信session失败: " + e.getMessage());
        }
    }
    
    /**
     * 解密微信手机号数据
     */
    public String decryptWechatPhone(String encryptedData, String iv, String sessionKey) {
        log.info("=== 开始解密微信手机号 ===");
        
        
        try {
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] ivBytes = Base64.getDecoder().decode(iv);
            
            // AES解密
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);
            String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);
            
            log.info("解密后的数据: {}", decryptedData);
            
            // 解析JSON获取手机号
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(decryptedData);
            
            String phoneNumber = jsonNode.get("phoneNumber").asText();
            log.info("解密得到手机号: {}", phoneNumber);
            log.info("=== 微信手机号解密成功 ===");
            
            return phoneNumber;
            
        } catch (Exception e) {
            log.error("解密微信手机号失败", e);
            throw new RuntimeException("解密微信手机号失败: " + e.getMessage());
        }
    }
    
    /**
     * 微信Session信息类
     */
    public static class WechatSessionInfo {
        private String openid;
        private String sessionKey;
        
        public String getOpenid() {
            return openid;
        }
        
        public void setOpenid(String openid) {
            this.openid = openid;
        }
        
        public String getSessionKey() {
            return sessionKey;
        }
        
        public void setSessionKey(String sessionKey) {
            this.sessionKey = sessionKey;
        }
    }
}
